package com.lj.back.manage.scaffold.module.kaptcha.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lj.back.manage.scaffold.common.enums.ResponseEnum;
import com.lj.back.manage.scaffold.common.exception.MyException;
import com.lj.back.manage.scaffold.common.response.ResponseCodeConstant;
import com.lj.back.manage.scaffold.module.kaptcha.DO.KaptchaDO;
import com.lj.back.manage.scaffold.module.kaptcha.dao.KaptchaDao;
import com.lj.back.manage.scaffold.module.kaptcha.service.KaptchaService;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Priority;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * @author lv
 * @version 1.0.0
 */
@Service
@Priority(2)
@AllArgsConstructor
public class JdbcKaptchaServiceImpl implements KaptchaService {

    private final KaptchaDao kaptchaDao;

    @Override
    public boolean record(String key, String code, long expireTime) {
        KaptchaDO kaptcha = new KaptchaDO();
        kaptcha.setId(key);
        kaptcha.setCode(code);
        kaptcha.setExpireTime(LocalDateTime.now().plusSeconds(expireTime));
        kaptchaDao.insert(kaptcha);
        return true;
    }

    @Override
    public ResponseEnum valid(String key, String code) {
        String codeByJDBC = getCode(key);
        if (StringUtils.isBlank(codeByJDBC)){
            return ResponseEnum.CODE_GRAPH_INVALID;
        }
        //验证失败
        if (!Objects.equals(codeByJDBC,code)){
            return ResponseEnum.CODE_GRAPH_ERROR;
        }
        //成功
        return ResponseEnum.SUCCESS;
    }

    @Override
    public boolean delete(String key) {
        //删除验证码
        kaptchaDao.deleteById(key);
        return true;
    }

    @Override
    public String getCode(String key) {
        QueryWrapper<KaptchaDO> queryWrapper = new QueryWrapper<KaptchaDO>().eq("id", key);
        List<KaptchaDO> kaptchaDOS = kaptchaDao.selectList(queryWrapper);
        //不存在
        if (kaptchaDOS == null || kaptchaDOS.isEmpty()){
            return null;
        }
        //删除验证码
        int count = kaptchaDao.deleteById(key);
        if (count != kaptchaDOS.size()){
            throw new MyException(ResponseCodeConstant.CODE_GRAPH_ERROR, "删除验证码失败，总共有"+kaptchaDOS.size()+"条记录，删除"+count+"条记录");
        }
        // 非法 同一个key数据库存在多条记录  即uuid重复
        if (kaptchaDOS.size() != 1){
            throw new MyException(ResponseEnum.CODE_REPEAT);
        }
        KaptchaDO kaptchaDO = kaptchaDOS.get(0);
        //已失效
        if (LocalDateTime.now().isBefore(kaptchaDO.getExpireTime())){
            throw new MyException(ResponseEnum.CODE_GRAPH_INVALID);
        }
        return kaptchaDO.getCode();
    }
}
